/*
 * Populating Next Right Pointers in Each Node II
Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
For example,
Given the following binary tree,
         1
       /  \
      2    3
     / \    \
    4   5    7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
 */
package com.xinpan.exercise;

public class PopulatingNextRightPointer2 {
    public void connect(TreeLinkNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(root == null)
            return;
        root.next = null;
        
        conSub(root.right, null);
        conSub(root.left, root.right);
    }
    
    public void conSub(TreeLinkNode root, TreeLinkNode next)
    {
        if(root == null)
            return;
        root.next = next;
        
        while(next != null)
        {
            if(next.left != null)
            {
                next = next.left;
                break;
            }
            else if(next.right != null)
            {
                next = next.right;
                break;
            }
            else
                next = next.next;
        }
        
        if(root.right != null)
        {
            conSub(root.right, next);
            conSub(root.left, root.right);
        }
        else
            conSub(root.left, next);    
    }
    
    class TreeLinkNode {
    	      int val;
    	      TreeLinkNode left, right, next;
    	      TreeLinkNode(int x) { val = x; }
    	  }
}
